//
//  MZContactsViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 17/02/12.
//  Copyright 2012 CFA de Bobigny - COIFFURE. All rights reserved.
//

#import "MZContactsViewController.h"
#import "MZInfosViewController.h"

@implementation MZContactsViewController

@synthesize contactsArray;
@synthesize currentContact;

#pragma mark -
#pragma mark View lifecycle


/*
- (void)showInfo:(id)sender
{
    NSLog(@"Info button tapped, show modal view");
    MZInfosViewController *mzInfosViewController = [[MZInfosViewController alloc]
                                                    initWithNibName:@"MZInfosViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mzInfosViewController];
    mzInfosViewController.title = @"Informations";
    [mzInfosViewController release];
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
									  initWithTitle:@"Fermer"
									  style:UIBarButtonItemStyleBordered
									  target:mzInfosViewController
									  action:@selector(GoBack:)];
	mzInfosViewController.navigationItem.leftBarButtonItem = barButtonItem;
    [self.tabBarController presentModalViewController:navController animated:YES];
    [navController release];
    
}
*/

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"contact_icon"];
    }
    return self;
}

- (void)initContacts {
	contactsArray = [[NSMutableArray alloc] init];
	NSMutableDictionary *contactDict;
	contactDict = [[NSMutableDictionary alloc] init];
	[contactDict setValue:@"Secrétariat" forKey:@"Titre"];
	[contactDict setValue:@"mz.programme@gmail.com" forKey:@"Adresse"];
	[contactsArray addObject:contactDict];
	[contactDict release];
	contactDict = [[NSMutableDictionary alloc] init];
	[contactDict setValue:@"Souscrire un majliss" forKey:@"Titre"];
	[contactDict setValue:@"mz.programme@gmail.com" forKey:@"Adresse"];
	[contactsArray addObject:contactDict];
	[contactDict release];
	/*
    contactDict = [[NSMutableDictionary alloc] init];
	[contactDict setValue:@"Pôle financier" forKey:@"Titre"];
	[contactDict setValue:@"financier@mehfilezainab.com" forKey:@"Adresse"];
	[contactsArray addObject:contactDict];
	[contactDict release];
	contactDict = [[NSMutableDictionary alloc] init];
	[contactDict setValue:@"Pôle social" forKey:@"Titre"];
	[contactDict setValue:@"social@mehfilezainab.com" forKey:@"Adresse"];
	[contactsArray addObject:contactDict];
	[contactDict release];	
    */
}

- (void)viewDidLoad {
    [super viewDidLoad];
	[self initContacts];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    //return <#number of sections#>;
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //return <#number of rows in section#>;
	NSLog(@"Count of contacts to display : %d",[contactsArray count]);
	return [contactsArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    [cell.textLabel setText:[[contactsArray objectAtIndex:indexPath.row] objectForKey:@"Titre"]];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	currentContact = [indexPath row];
	[self showPicker:currentContact];
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *) indexPath {
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
    currentContact = [indexPath row];
	[self showPicker:currentContact];
	
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

-(void)showPicker:(NSInteger) index
{
	// This sample can run on devices running iPhone OS 2.0 or later  
	// The MFMailComposeViewController class is only available in iPhone OS 3.0 or later. 
	// So, we must verify the existence of the above class and provide a workaround for devices running 
	// earlier versions of the iPhone OS. 
	// We display an email composition interface if MFMailComposeViewController exists and the device can send emails.
	// We launch the Mail application on the device, otherwise.
	
	Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil)
	{
		NSLog(@"MFMailComposeViewController class exists for this version of OS");
		
		// We must always check whether the current device is configured for sending emails
		if ([mailClass canSendMail])
		{
			NSLog(@"Device configured for sending mail");
			[self displayComposerSheet:index];
		}
		else
		{
			NSLog(@"Device not configured to send mail, launch Mail App");
			[self launchMailAppOnDevice];
		}
	}
	else
	{
		NSLog(@"MFMailComposeViewController class does not exist, launch Mail App");
		[self launchMailAppOnDevice];
	}
}


#pragma mark -
#pragma mark Compose Mail

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayComposerSheet:(NSInteger)index
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
    if(index==0)
    {
        [picker setSubject:@"Renseignements"];
    }
	if(index==1)
    {
        [picker setSubject:@"Souscription d'un majliss"];
    }
	
	// Set up recipients
	NSArray *toRecipients = [NSArray arrayWithObject:[[contactsArray objectAtIndex:currentContact] objectForKey:@"Adresse"]]; 
	//NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"]; 
	//NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
	//NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
	
	[picker setToRecipients:toRecipients];
	//[picker setCcRecipients:ccRecipients];	
	//[picker setBccRecipients:bccRecipients];
	
	// Attach an image to the email
	/*
	NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"png"];
    NSData *myData = [NSData dataWithContentsOfFile:path];
	[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"rainy"];
	*/
	
	// Fill out the email body text
	/*
	NSString *emailBody = @"It is raining in sunny California!";
	[picker setMessageBody:emailBody isHTML:NO];
	*/
	
	//[self presentModalViewController:picker animated:YES];
    [self presentViewController:picker animated:YES completion:nil];
    [picker release];
}


// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{	
	NSString *message;
	//message.hidden = NO;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			//message.text = @"Result: canceled";
			message = @"Envoi annulé";
			break;
		case MFMailComposeResultSaved:
			//message.text = @"Result: saved";
			message = @"Message sauvegardé";
			break;
		case MFMailComposeResultSent:
			//message.text = @"Result: sent";
			message = @"Message envoyé";
			break;
		case MFMailComposeResultFailed:
			//message.text = @"Result: failed";
			message = @"Echec";
			break;
		default:
			//message.text = @"Result: not sent";
			message = @"Message non envoyé";
			break;
	}
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Mehfile Zainab" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
	//[self dismissModalViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -
#pragma mark Workaround

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
	//NSString *recipients = @"mailto:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!";
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=Demande de renseignements",[[contactsArray objectAtIndex:currentContact] objectForKey:@"Adresse"]];
	//NSString *body = @"&body=It is raining in sunny California!";
	
	//NSString *email = [NSString stringWithFormat:@"%@", recipients, body];
	NSString *email = [NSString stringWithFormat:@"%@", recipients];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}


@end

